package com.zwps.biz.controller.listener.rabbitmq;

import com.rabbitmq.client.Channel;
import com.zwps.biz.domain.service.LogApiService;
import com.zwps.biz.domain.service.LogMessageService;
import com.zwps.common.core.context.RabbitmqDefine;

import lombok.AllArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.io.IOException;
import static org.springframework.amqp.core.ExchangeTypes.TOPIC;

/**
 * 
 * @ClassName: LogMessageMQListener
 * @Description:
 * @author lyh
 * @date 2023年10月19日 下午1:49:27
 *
 */
@Component
@ConditionalOnProperty("spring.rabbitmq.enable")
@AllArgsConstructor
public class LogMQListener {

    private LogMessageService logMessageService;

    private LogApiService logApiService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitmqDefine.LOG_MESSAGE_QUEUE, durable = "false"), // 配置队列
            exchange = @Exchange(value = RabbitmqDefine.EXCHANGE_NAME, type = TOPIC), // 配置交换机，交换机类型
            key = { RabbitmqDefine.LOG_MESSAGE_ROUTE } // 配置路由
    ), ackMode = "MANUAL")
    public void messageLogListener(Channel channel, Message message) throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        String body = new String(message.getBody());
        logMessageService.addLogMessage(body);
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitmqDefine.LOG_API_QUEUE, durable = "false"), // 配置队列
            exchange = @Exchange(value = RabbitmqDefine.EXCHANGE_NAME, type = TOPIC), // 配置交换机，交换机类型
            key = { RabbitmqDefine.LOG_API_ROUTE } // 配置路由
    ), ackMode = "MANUAL")
    public void apiLogListener(Channel channel, Message message) throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        String body = new String(message.getBody());
        logApiService.addLogApi(body);
    }

}
